<template>
  <transition>
    <div v-if="visible" class="detail-main">
      <el-page-header @back="handleClose" :icon="null" class="detail-header">
        <template #title>
          <div class="detail-header-title">
            <el-icon>
              <key />
            </el-icon>
            修改密码
          </div>
        </template>
        <template #content>
          密码信息
        </template>
        <template #extra>
          <div style="flex: auto">
            <el-button type="primary" @click="handleOk(formRef)" :loading="state.subLoading" :icon="Select">
              保存
            </el-button>
            <el-button @click="handleClose" :icon="Back">返回列表</el-button>
          </div>
        </template>
      </el-page-header>
      <div class="detail-form">
        <el-form ref="formRef" :model="formState" label-width="auto" :rules="rules" v-loading="state.subLoading">
          <el-row :gutter="20">
           <el-col :span="20" :offset="1">
              <el-form-item prop="password" label="新密码">
                <el-input id="password" type="password"  class="w-500" v-model="formState.password" placeholder="请输入新密码" show-password clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
           <el-col :span="20" :offset="1">
              <el-form-item prop="confirmPassword" label="确认密码">
                <el-input id="confirmPassword" type="password"  class="w-500" v-model="formState.confirmPassword" placeholder="请确认密码" show-password clearable />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
  </transition>
</template>
<script setup name="ResetPwdForm">
import {UserApi} from '@/api/system/user';
import useCurrentInstance from '@/hooks/useCurrentInstance';
import {rePasswordState, setSubLoading, state} from "@/views/system/user/index";
import {CommonApi} from "@/api/common";
import {CacheUtil} from "@/utils/cacheUtil";
import {JSEncrypt} from "jsencrypt";
import {Back, Key, Select} from '@element-plus/icons-vue'

const {proxy} = useCurrentInstance();
const emits = defineEmits(["refreshData"]);
let formState = toRef(rePasswordState);
const formRef = ref();
const visible = ref(false)
const props = defineProps({
  id: {
    type: String,
    required: true
  },
  drawer: {
    type: Boolean,
    required: true
  }
})

let validatePass = (rule, value) => {
  if (value === "") {
    return Promise.reject("请再次输入密码");
  } else if (value !== formState.value.password) {
    return Promise.reject('两次输入密码不一致!');
  }
  return Promise.resolve();
};

let validatePassForm = (rule, value) => {
  if (value === "") {
    return Promise.reject("请输入密码");
  }
  if (value.length < 6 || value.length > 16) {
    return Promise.reject("密码长度必须在6到16个字符之间");
  }
  if (!/[0-9]/.test(value) || !/[a-zA-Z]/.test(value)) {
    return Promise.reject("密码必须包含数字和字母");
  }
  return Promise.resolve();
}

const rules = reactive({
  password: [{required: true, validator: validatePassForm, trigger: 'blur'}],
  confirmPassword: [{required: true, validator: validatePass,  trigger: ['change', 'blur']}],
});

function handleOk(formEl) {
  if (!formEl) return
  formEl.validate(async (valid, fields) => {
    if (valid) {
      setSubLoading(true);
      const result = await CommonApi.getPublicKey();
      if (result) {
        const {publicKey, sessionGenerateId} = result;
        CacheUtil.setSessionGenerateId(sessionGenerateId);
        const encryptor = new JSEncrypt();
        encryptor.setPublicKey(publicKey);
        if (formState.value.password !== formState.value.confirmPassword) {
          proxy.$message.error('两次密码不一致');
          setSubLoading(false);
          return;
        }
        const password = encryptor.encrypt(formState.value.password);
        const confirmPassword = encryptor.encrypt(formState.value.confirmPassword);
        const res = await UserApi.rePassword({id: props.id, password,confirmPassword, sessionGenerateId});
        if (res.success) {
          proxy.$message.success(res.message);
          handleClose();
        } else {
          proxy.$message.error(res.message);
        }
      } else {
        proxy.$message.error("操作失败");
      }
      setSubLoading(false);
    } else {
      console.log('error submit!', fields)
    }
  })
}

//关闭弹窗
function handleClose() {
  formRef.value?.resetFields()
  emits('refreshData');
  resetData();
}

//重置数据
function resetData() {
  formState.value = rePasswordState;
}
//监听props.visible 值得变化
watch(() => props.drawer, v => {
  visible.value = v
})
defineExpose({
})

</script>

<style scoped></style>
